#!/usr/bin/env python
# encoding: utf-8

#  Copyright (c) 2007 Freight Logistics, Inc.
#  Author Ryan Parrish <rparrish@freightlogistics.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#TODO: put everything under the folder of the solution name
import os
import os.path
import shutil
import cPickle as pickle


import MySQLdb
from configobj import ConfigObj
import pysvn

import svcs

def create_dir(folder):
    __doc__ = """if folder does not exist, create it.  
    Otherwise if it does exist remove it and then recreate it"""
    if os.path.exists(folder) == False:
        os.mkdir(folder)
    else:
        shutil.rmtree(folder)
        os.mkdir(folder)

config = ConfigObj('config.cfg')
solution = svcs.ServoyVCS(config)

############################    
#first get the form methods#
############################
print 'starting the form methods'

#create_dir(config['EXPORT_PATH'] + '/' + config['FORM_METHOD_FOLDER'])
os.chdir(config['EXPORT_PATH'] + '/' + config['FORM_METHOD_FOLDER'])

elements = solution.get_elements(config['SOLUTION_NAME'], 'form_method_name')
for element_id in elements:
    element_name = elements[element_id]['property_value']
    parent = solution.get_parent_form(config['SOLUTION_NAME'], 
                                      elements[element_id]['parent_element_id'])
        
    if os.path.exists(parent['form_name']) == False:
        os.mkdir(parent['form_name'])
    
    #loop through all the revisions to find the highest one.
    prev_rev = 0
    for rev in elements[element_id]['revisions']:
        if rev['revision'] > prev_rev:
            revision = rev
    
    methodText = solution.get_method_text('form_method', element_id)
    methodPath = config['FORM_METHOD_FOLDER'] + parent['form_name'] + '/' + element_name
    
    metaData = dict(elementID = element_id,
                    methodName = element_name,
                    elementNamePropertyID = revision['element_property_id'],
                    revision = revision['revision'],
                    elementType = 'form_method',
                    methodPath = methodPath,
                    parent = parent['form_name'])
    
    solution.write_method(methodText, metaData, metaData['parent'])
        
print 'finshed the form methods'

##############################
#now get the global methods  #
##############################
print 'starting the global methods'

#create_dir(config['EXPORT_PATH'] + '/' + config['GLOBAL_METHOD_FOLDER'])
os.chdir(config['EXPORT_PATH'] + '/' + config['GLOBAL_METHOD_FOLDER'])

elements = solution.get_elements(config['SOLUTION_NAME'], 'global_method_name')
for element_id in elements:
    element_name = elements[element_id]['property_value']
    #loop through all the revisions to find the highest one.
    prev_rev = 0
    for rev in elements[element_id]['revisions']:
        if rev['revision'] > prev_rev:
            revision = rev
            
    methodText = solution.get_method_text('global_method', element_id)
    
    metaData = dict(elementID = element_id,
                    methodName = element_name,
                    elementNamePropertyID = revision['element_property_id'],
                    revision = revision['revision'],
                    elementType = 'global_method',
                    methodPath = config['GLOBAL_METHOD_FOLDER'] + element_name)
    
    solution.write_method(methodText, metaData)
        
print 'finshed the global methods'

##############################
#now get the calcs           #
##############################
print 'starting the calc methods'

#create_dir(config['EXPORT_PATH'] + '/' + config['CALCS_FOLDER'])
os.chdir(config['EXPORT_PATH'] + '/' + config['CALCS_FOLDER'])

elements = solution.get_elements(config['SOLUTION_NAME'], 'calc_name')
for element_id in elements:
    element_name = elements[element_id]['property_value']
    #loop through all the revisions to find the highest one.
    prev_rev = 0
    for rev in elements[element_id]['revisions']:
        if rev['revision'] > prev_rev:
            revision = rev
            
    methodText = solution.get_method_text('calc', element_id)
    
    metaData = dict(elementID = element_id,
                    methodName = element_name,
                    elementNamePropertyID = revision['element_property_id'],
                    revision = revision['revision'],
                    elementType = 'calc',
                    methodPath = config['CALCS_FOLDER'] + element_name)
    
    solution.write_method(methodText, metaData)
        
print 'finshed the calc methods'

print 'updating repo with new files'
client = pysvn.Client()
changes = client.status(config['EXPORT_PATH'])
unversioned = [f.path for f in changes if f.text_status == pysvn.wc_status_kind.unversioned]
for i in unversioned:
    client.add(i)
client.checkin(unversioned, "Adding new files from repo")

print 'housekeeping, clearing out removed files'

for root, dirs, files in os.walk(config['EXPORT_PATH']):
    if '.svn' in dirs:
        dirs.remove('.svn')  # don't visit svn directories
    for fileName in files:
        if fileName[0] != '.': 
            continue  #we just want the metadata files
        metaDataFile = open(root + '/' + fileName, 'rb')
        metaData = pickle.load(metaDataFile)
	metaDataFile.close()
	status = solution.check_status(metaData['elementNamePropertyID'])
	if status is False:
	    methodFile = config['EXPORT_PATH'] + '/' + metaData['methodPath'] + '.servoy'
	    client.remove(methodFile)
	    client.remove(metaDataFile.name)
	    fileList = [methodFile, metaDataFile.name]
	    client.checkin(fileList, "Removing deleted method %s" % (metaData['methodName']) )

print 'done.'
